<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=3.0, user-scalable=yes, viewport-fit=cover" />
		<title>拍照</title>
	</head>
	<body>
		<video id="video" width="98%" height="240" style="border:0px solid red;"></video>
		<div style="text-align: center;margin-top: 10px;">
			<a href="javascript:void()" onclick="startRecord();">开始录制</a>
			<a href="javascript:void()" onclick="stopRecord();">停止录制</a>
		</div>
		<div style="text-align: center;margin-top: 10px;color: #c3c3c3;" id="status">未开始</div>

		<div style="text-align: center;"><a href="javascript:void()" onclick="playRecord();">播放录制</a></div>
		<video id="record" width="98%" height="240" style="border:1px solid red;" controls></video>
		<script>
			let video = document.getElementById("video");
			let statusDiv = document.getElementById("status");
			let record = document.getElementById("record");
			let recording = false;
			let chunks = [];
			let mediaRecorder = null;

			// 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
			if (navigator.mediaDevices === undefined) {
				navigator.mediaDevices = {};
			}

			// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
			// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function(constraints) {

					// 首先，如果有getUserMedia的话，就获得它
					var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

					// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
					if (!getUserMedia) {
						return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
					}

					// 否则，为老的navigator.getUserMedia方法包裹一个Promise
					return new Promise(function(resolve, reject) {
						getUserMedia.call(navigator, constraints, resolve, reject);
					});
				}
			}

			let constraints = {
				audio: true,
				video: {
					facingMode: {
						exact: "environment"
					},
					with: 1280,
					height: 720
				}
			};
			navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
				// 旧的浏览器可能没有srcObject
				if ("srcObject" in video) {
					video.srcObject = stream;
				} else {
					// 防止在新的浏览器里使用它，应为它已经不再支持了
					video.src = window.URL.createObjectURL(stream);
				}
				video.onloadedmetadata = function(e) {
					// video.play();
				};

				mediaRecorder = new MediaRecorder(stream);
				mediaRecorder.ondataavailable = (e) => {
					if (e.data.size > 0) {
						chunks.push(e.data);
					}
				};

			}).catch(function(err) {
				console.log(err.name + ": " + err);
			});


			function startRecord() {
				mediaRecorder.start(1000);
				statusDiv.innerHTML = "录制中";
				video.play();
				recording = true;
				console.log("录制开始");
			}

			function stopRecord() {
				video.srcObject.getTracks().forEach((track) => track.stop());
				mediaRecorder.stop();

				const blob = new Blob(chunks, {
					type: "video/mp4;codecs=h264,aac"
				});
				chunks = [];
				const audioURL = URL.createObjectURL(blob);
				console.log("录制结束");
				statusDiv.innerHTML = "结束录制";
				recording = false;

				// playVideo.href = audioURL;
				// playVideo.download = "录屏_" + new Date().getTime() + ".webm"; 

				record.src = audioURL;
				
				let formate = new FormData();
				formate.append("id", "20250828-170801");
				formate.append("file", blob, "video.mp4");
				
				fetch(
						"http://192.168.24.157:8080/dophen/testReceiveMP4", {
							method: "POST",
							body: formate
						}
					).then(response => response.text())
					.then(data => console.log(data))
					.catch(error => console.error(error));
			}

			function playRecord() {
				console.log("播放录制");
				record.play();
			}

			//动态刷新 5s
			window.setInterval(function() {
				if (chunks.length >= 60) {

					const blob = new Blob(chunks, {
						type: "video/mp4"
					});
					chunks = [];
					let formate = new FormData();
					formate.append("id", "20250828-170801");
					formate.append("file", blob, "video.mp4");

					fetch(
							"http://192.168.24.157:8080/dophen/testReceiveMP4", {
								method: "POST",
								body: formate
							}
						).then(response => response.text())
						.then(data => console.log(data))
						.catch(error => console.error(error));

				}
			}, 5000);
		</script>
	</body>
</html>